package edu.suda.cxtz.controller;

import cn.hutool.core.collection.CollectionUtil;
import edu.suda.cxtz.entity.Dept;
import edu.suda.cxtz.entity.User;
import edu.suda.cxtz.entity.dto.DeptDto;
import edu.suda.cxtz.entity.dto.DeptQueryCriteria;
import edu.suda.cxtz.entity.dto.UserDto;
import edu.suda.cxtz.service.DeptService;
import edu.suda.cxtz.modules.exception.BadRequestException;
import edu.suda.cxtz.service.UserService;
import edu.suda.cxtz.utils.DtoEntityUtil;
import edu.suda.cxtz.utils.PageResult;
import edu.suda.cxtz.utils.PageUtil;
import edu.suda.cxtz.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequiredArgsConstructor
@Tag(name = "部门管理")
@RequestMapping("/api/dept")
@ResponseBody
public class DeptController {
    private final DeptService deptService;
    private final UserService userService;
    private static final String ENTITY_NAME = "dept";
    private final DtoEntityUtil mapper;

    @GetMapping(value = "/query")
    @PreAuthorize("@el.check('user:list', 'dept:list')")
    public ResponseEntity<PageResult<DeptDto>> queryDept(DeptQueryCriteria criteria) throws Exception {
        List<DeptDto> deptDtoList = deptService.queryAll(criteria, true);
        return new ResponseEntity<>(PageUtil.toPage(deptDtoList, deptDtoList.size()), HttpStatus.OK);
    }

    @Operation(summary = "查询部门")
    @GetMapping("/queryall")
    public ResponseEntity<List<DeptDto>> queryAllDept() throws Exception {
        List<Dept> list = deptService.queryAll();
        return new ResponseEntity<>(mapper.trans(list,DeptDto.class), HttpStatus.OK);
    }
    @Operation(summary = "获取部门列表")
    @PostMapping("/superior")
    @PreAuthorize("@el.check('user:list','dept:list')")
    public ResponseEntity<Object> getDeptSuperior(@RequestParam(defaultValue = "false") Boolean exclude) {
        UserDto user = userService.findById(SecurityUtils.getCurrentUserId());
        DeptDto deptDto = deptService.findById(user.getDept().getId());
        List<DeptDto> deptDtos = deptService.getSuperior(deptDto, new ArrayList<>());
        Set<DeptDto> deptSet = new LinkedHashSet<>(deptDtos);
//        for (Long id : ids) {
//            DeptDto deptDto = deptService.findById(id);
//            List<DeptDto> depts = deptService.getSuperior(deptDto, new ArrayList<>());
//            if(exclude){
//                for (DeptDto dept : depts) {
//                    if(dept.getId().equals(deptDto.getPid())) {
//                        dept.setSubCount(dept.getSubCount() - 1);
//                    }
//                }
//                // 编辑部门时不显示自己以及自己下级的数据，避免出现PID数据环形问题
//                depts = depts.stream().filter(i -> !ids.contains(i.getId())).collect(Collectors.toList());
//            }
//            deptSet.addAll(depts);
//        }
        return new ResponseEntity<>(deptService.buildTree(new ArrayList<>(deptSet)),HttpStatus.OK);
    }

//    @Log("新增部门")
    @Operation(summary = "新增部门")
    @PostMapping
    @PreAuthorize("@el.check('dept:add')")
    public ResponseEntity<Object> createDept(@Validated @RequestBody Dept resources){
        if (resources.getId() != null) {
            throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
        }
        deptService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

//    @Log("修改部门")
    @Operation(summary = "修改部门")
    @PutMapping
    @PreAuthorize("@el.check('dept:edit')")
    public ResponseEntity<Object> updateDept(@Validated(Dept.Update.class) @RequestBody Dept resources){
        deptService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

//    @Log("删除部门")
    @Operation(summary = "删除部门")
    @DeleteMapping
    @PreAuthorize("@el.check('dept:del')")
    public ResponseEntity<Object> deleteDept(@RequestBody Set<Long> ids){
        Set<DeptDto> deptDtos = new HashSet<>();
        for (Long id : ids) {
            List<Dept> deptList = deptService.findByPid(id);
            deptDtos.add(deptService.findById(id));
            if(CollectionUtil.isNotEmpty(deptList)){
                deptDtos = deptService.getDeleteDepts(deptList, deptDtos);
            }
        }
        // 验证是否被角色或用户关联
        deptService.verification(deptDtos);
        deptService.delete(deptDtos);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
